package com.xs.mvc.handler;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.xs.mvc.common.Ajax;
import com.xs.mvc.exception.BusinessExcetion;

/**
 * Created by Administrator on 2019/1/30.
 */
public class BaseGlobalExceptionHandler {
    protected static final Logger logger =  Logger.getLogger(BaseGlobalExceptionHandler.class);;
    protected ModelAndView handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e, String viewName, HttpStatus status) throws Exception {
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
            throw e;
        String errorMsg =  e.getMessage() ;
        String errorStack = getExceptionDetail(e);
        logger.error("RequestUrl:"+ req.getRequestURI()+"\n"+errorStack);
        if (Ajax.isAjaxRequestInternal(req)) {
            return handleAjaxError(rsp, errorMsg, status);
        }
        return handleViewError(req.getRequestURL().toString(), errorStack,e, errorMsg, viewName);
    }

    protected ModelAndView handleViewError(String url, String errorStack, Exception e,String errorMessage, String viewName) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", errorStack);
        mav.addObject("url", url);
        mav.addObject("message", errorMessage);
        mav.addObject("timestamp", new Date());
        mav.setViewName(viewName);
        return mav;
    }

    protected ModelAndView handleAjaxError(HttpServletResponse rsp, String errorMessage, HttpStatus status) throws IOException {
        rsp.setCharacterEncoding("UTF-8");
        rsp.setStatus(status.value());
        PrintWriter writer = rsp.getWriter();
        Map<String,Object> obj = new HashMap<String,Object>();
        obj.put("errorMessage", errorMessage);
        obj.put("timestamp", new Date());
        writer.write(JSON.toJSONString(obj));
        writer.flush();
        return null;
    }

    private String getExceptionDetail(Exception e){
    	StringBuffer buffer = new StringBuffer();
    	if(e!=null){
    		 synchronized (this) {
    	            // Print our stack trace
    				buffer.append(e);
    				buffer.append("\n");
    	            StackTraceElement[] trace = e.getStackTrace();
    	            for (StackTraceElement traceElement : trace){
    	               	buffer.append("\tat "+traceElement);
    	            	buffer.append("\n");
    	            }
    	        }
    	}
    	return buffer.toString();
    }


}
